//
//  CXLStatusCellPictureView.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/22.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit
import SDWebImage

/// 配图界面图片间距
private let CXLStatusCellPictureViewMargin:CGFloat = 8

/// 重用标示
private let CXLStatusCellPictureViewCellID = "CXLStatusCellPictureViewCellID"

/// 微博配图视图
class CXLStatusCellPictureView: UICollectionView {

    /// 单条微博数据视图模型
    var statusViewModel:StatusViewModel?{
        
        didSet{
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return caculateViewSize()
    }
    
    //MARK:- 构造函数 布局layout
    init(){
        
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = CXLStatusCellPictureViewMargin
        
        layout.minimumLineSpacing = CXLStatusCellPictureViewMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        dataSource = self
        
        delegate = self
        
        registerClass(CXLStatusPictureCell.self, forCellWithReuseIdentifier: CXLStatusCellPictureViewCellID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

// MARK: - 数据源方法
extension CXLStatusCellPictureView :UICollectionViewDataSource, UICollectionViewDelegate {
    
    
    ///  选中collectionView cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 发布通知,传递当前图片信息
        NSNotificationCenter.defaultCenter().postNotificationName( WBStatusPictureSelectedCellKey , object: self, userInfo: [WBStatusPictureSelectedIndexPathKey: indexPath, WBStatusPictureSelectedURLsKey : statusViewModel!.pictureUrls!])
        
        transitionPresentedEndFrame(indexPath)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return statusViewModel?.pictureUrls?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CXLStatusCellPictureViewCellID, forIndexPath: indexPath) as! CXLStatusPictureCell
        
        let url = statusViewModel?.pictureUrls![indexPath.row]
        
        cell.iconView.sd_setImageWithURL(url, placeholderImage: nil, options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed])
        
        cell.gifIcon.hidden = ((url?.absoluteString ?? "") as NSString).pathExtension.lowercaseString != "gif"
        
        return cell
    }

}

// MARK: - 自定义转场动画,modal时 的代理方法
extension CXLStatusCellPictureView : CXLTransitionPresentedDelegate{
    
    func imageViewForTranstionPresented(indexPath: NSIndexPath) -> UIImageView {
        
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        let urlString = statusViewModel?.pictureUrls![indexPath.item].absoluteString
        
        iv.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString!)
        
        return iv
    }
    
    func transitionPresentedStartFrame(indexPath: NSIndexPath) -> CGRect {
        let cell = self.cellForItemAtIndexPath(indexPath) as! CXLStatusPictureCell
        
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return rect
    }
    
    func transitionPresentedEndFrame(indexPath: NSIndexPath) -> CGRect {
        
        let cell = self.cellForItemAtIndexPath(indexPath) as! CXLStatusPictureCell
        
        guard let image = cell.iconView.image else{
            return CGRectZero
        }
        
        let width = UIScreen.mainScreen().bounds.width
        
        let height = image.size.height * width / image.size.width
        
        var y :CGFloat = 0
        
        let screenH = UIScreen.mainScreen().bounds.height
        
        if height < screenH {
            
            y = (screenH - height) * 0.5
        }
        
        let rect = CGRect(x: 0, y: y, width: width, height: height)
        
        return rect
    }
}

// MARK: - 计算collectionView的size
extension CXLStatusCellPictureView {
   
    private func caculateViewSize() ->CGSize{
        
        let count = statusViewModel?.pictureUrls?.count ?? 0
        
        if count == 0 {
            
            return CGSizeZero
            
        }
        
        let rowCount:CGFloat = 3
        
        let maxPictureWidth = UIScreen.mainScreen().bounds.width - 2 * statusCellMargin //- 32
        
        let pictureW = (maxPictureWidth - (rowCount - 1) * CXLStatusCellPictureViewMargin) / rowCount
        
        var size = CGSize(width: pictureW, height: pictureW)
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = size
        
        
        if count == 1 {
            
            let key = statusViewModel?.pictureUrls![0].absoluteString
            
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
                
                size = image.size
                
            }
            
            if size.width < 40 {
                
                size.width = 40
            }
            
            if size.width > 300 {
                
                let w:CGFloat = 300
                
                let h = size.height * 300 / size.width
                
                size = CGSize(width: w, height: h)
            }
            
            layout.itemSize = size
            
            return CGSize(width: size.width + 1, height: size.height + 1)
        }
        
        if count == 4 {
            
            let w = 2 * pictureW + CXLStatusCellPictureViewMargin + 1
            
            return CGSize(width: w, height: w)
        }
        
        if count > 0 {
            
            let row = CGFloat((count - 1 ) / 3 + 1)
            
            let h = pictureW * row  + CXLStatusCellPictureViewMargin * (row - 1)
            
            return CGSize(width: maxPictureWidth + 1, height: h)
        }
        
        return size
    }
}

/// 自定义 collectionCell
class CXLStatusPictureCell:UICollectionViewCell{
    
    //MARK:-构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(iconView)
        iconView.addSubview(gifIcon)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        gifIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(iconView.snp_right)
            make.bottom.equalTo(iconView.snp_bottom)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 配图
    lazy var iconView:UIImageView = {
       
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        
        iv.clipsToBounds = true
        
        return iv
    }()

    // gif标记
    private lazy var gifIcon:UIImageView = {
        let iv = UIImageView()
        iv.image = UIImage(named: "timeline_image_gif")
        return iv
    }()
    
    
}
